﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using cde.UserControl;
using System.Text;
using System.IO;
using System.Collections.Generic;
using ConfigAndElse;
using Cit.CDE.Net.Module;
using cde.cache;
using cde.SystemCommon;
using Cit.CDE.Net.Module.Commons;
using Module;

public partial class main_comm_CsvDownload : UserControl.MenuPathPage
{
    private CDEEntityManager moto_em;
    private CDESearchCriteria sc;
    private char p_spritstr = ',';
    private string pageSize = string.Empty;
    private string pageStart = string.Empty;
    private string allSize = string.Empty;
    private string chkFlg = string.Empty;
    private string land_id = string.Empty;
    private Boolean chkdata = false;
    protected void Page_Load(object sender, EventArgs e)
    {
            string moto_EM_FN = Request.QueryString["EnFullName"];
            pageSize = Request.QueryString["PageSize"];
            pageStart = Request.QueryString["PageStart"];
            allSize = Request.QueryString["AllSize"];
            //land_id = languageCode;
            chkFlg = Request.QueryString["chkFlg"];
            this.v_hid_allSize.Value = allSize;
            this.v_hid_chkFlg.Value = chkFlg;
            this.v_hid_pageSize.Value = pageSize;
            this.v_hid_pageStart.Value = pageStart;
            this.v_hid_EnName.Value = moto_EM_FN;
            
            moto_em = CDEFactory.getEMByFullName(moto_EM_FN);
            //sc = (CDESearchCriteria)Session[CDEConstants.CONST_SESSION_SC];        
            sc = (CDESearchCriteria)Session[WEBConstants.SC_SESSION_ID + moto_em];
    }

    protected void cmdCSV_Click(object sender, EventArgs e)
    {
        if (this.rdoB1.Checked)
        {
            sc.PageSize = int.Parse(pageSize);
            sc.PageStart = int.Parse(pageStart);
        }
        else if (this.rdoB2.Checked)
        {
            sc.PageSize = int.Parse(allSize);
            sc.PageStart = int.Parse(pageStart);
        }
        else if (this.rdoB3.Checked)
        {
            sc.PageSize = int.Parse(pageSize);
            sc.PageStart = int.Parse(pageStart);
            this.chkdata = true;
        }
        else
        {
            sc.PageSize = int.Parse(this.txtDataCount.Text);
            sc.PageStart = 1;
        }
        //this.buttonTr.Visible = false;
        //this.imgTr.Visible = true;
        string templateFileName = "";
        if (this.rdoBCsv.Checked)
        {

            templateFileName = System.Configuration.ConfigurationManager.AppSettings["CSV_OUT_PATH"] + moto_em.Full_Name
                + DateTime.Now.ToString("yyyy-MM-dd") + ".csv";
            templateFileName = System.Web.HttpContext.Current.Server.MapPath(templateFileName);

            csvWrite(templateFileName);
            csvDownload(templateFileName);
        }
        else if (this.rdoBExcel.Checked)
        {
            templateFileName = System.Configuration.ConfigurationManager.AppSettings["CSV_OUT_PATH"] + moto_em.Full_Name
                + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
            templateFileName = System.Web.HttpContext.Current.Server.MapPath(templateFileName);

            excelWrite(templateFileName);
            excelDownload(templateFileName);
        }
        else
        {
            printWrite();
        }

        this.closeWindow();
    }

    protected void csvWrite(string templateFileName)
    {
        System.IO.StreamWriter sw = null;
        try
        {
            string[] aryChk = this.chkFlg.Split(',');
            int rowIndex = 0;
            int colIndex = 0;
            Boolean boolRowWrite = true;
            List<CDEEntity> listEntity = CDEService.LoadEntities(moto_em, sc);
            if (System.IO.File.Exists(templateFileName))
            {
                System.IO.File.Delete(templateFileName);
            }
            sw = new System.IO.StreamWriter(templateFileName, true, Encoding.GetEncoding("UTF-8"));
            foreach (CDEAttribute cdeAttrheader in moto_em.ListAttributes)
            {
                if (cdeAttrheader.DISP_type != "N" && cdeAttrheader.DISP_type != "H")
                {
                    if (colIndex == 0)
                    {
                        sw.Write(cdeAttrheader.Label);
                    }
                    else
                    {
                        sw.Write(p_spritstr.ToString() + cdeAttrheader.Label);
                    }
                }
                colIndex++;
            }
            sw.WriteLine();
            foreach (CDEEntity entity in listEntity)
            {
                colIndex = 0;
                if (this.chkdata)
                {
                    if (aryChk[rowIndex] == "0")
                    {
                        boolRowWrite = false;
                    }
                    else
                    {
                        boolRowWrite = true;
                    }
                    rowIndex++;
                }
                if (boolRowWrite)
                {
                    foreach (CDEAttribute cdeAttr in moto_em.ListAttributes)
                    {
                        if (colIndex == 0)
                        {
                            sw.Write(entity.get(cdeAttr.Name));
                        }
                        else
                        {
                            sw.Write(p_spritstr.ToString() + entity.get(cdeAttr.Name));
                        }
                        colIndex++;
                    }
                    sw.WriteLine();
                }
            }   
            
        }
        catch(Exception e)
        {
            UserControl.Log.SaveException(e);
        }
        finally
		{
			if (sw != null)
			{
				sw.Close();
			}
		}       
    }
    private void csvDownload(string templateFileName)
    {
        //ファイルダウンロードダイアログを表示する
        FileInfo DownloadFile = new FileInfo(templateFileName);
        if (DownloadFile.Exists == true)
        {
            Response.Clear();
            Response.ClearHeaders();
            Response.Buffer = false;
            Encoding encodeShiftJIS = Encoding.GetEncoding("UTF-8");
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename="
                + HttpUtility.UrlEncode("CSVTemplate.csv", encodeShiftJIS));
            Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            Response.WriteFile(DownloadFile.FullName);
            Response.Flush();
            DownloadFile.Delete();
           // Response.End();
        }
    }

    protected void excelWrite(string templateFileName)
    {
        if (this.rdoB1.Checked)
        {
            sc.PageSize = int.Parse(pageSize);
            sc.PageStart = int.Parse(pageStart);
        }
        else if (this.rdoB2.Checked)
        {
            sc.PageSize = int.Parse(allSize);
            sc.PageStart = int.Parse(pageStart);
        }
        else if (this.rdoB3.Checked)
        {
            sc.PageSize = int.Parse(pageSize);
            sc.PageStart = int.Parse(pageStart);
            this.chkdata = true;
        }
        else
        {
            sc.PageSize = int.Parse(this.txtDataCount.Text);
            sc.PageStart = 1;
        }
        try
        {
            string[] aryChk = this.chkFlg.Split(',');
            List<CDEEntity> listEntity = CDEService.LoadEntities(moto_em, sc);
            if (System.IO.File.Exists(templateFileName))
            {
                System.IO.File.Delete(templateFileName);
            }

            System.Data.DataTable dt = new System.Data.DataTable();
            System.Data.DataRow dr;
            foreach (CDEAttribute cdeAttrheader in moto_em.ListAttributes)
            {
                if (cdeAttrheader.DISP_type != "N" && cdeAttrheader.DISP_type != "H")
                {
                    dt.Columns.Add(new System.Data.DataColumn());
                }
            }

            //System.Data.DataRow drCount = dt.NewRow();
            //drCount[0] = 0;
            //drCount[1] = 0;
            //dt.Rows.Add(drCount);
            System.Data.DataRow drName = dt.NewRow();
            System.Data.DataRow drLabel = dt.NewRow();

            int colIndex = 0;
            foreach (CDEAttribute cdeAttrheader in moto_em.ListAttributes)
            {
                if (cdeAttrheader.DISP_type != "N" && cdeAttrheader.DISP_type != "H")
                {
                    drName[colIndex] = cdeAttrheader.Name;
                    drLabel[colIndex] = cdeAttrheader.Label;
                    colIndex++;
                }
            }
            dt.Rows.Add(drName);
            dt.Rows.Add(drLabel);

            if (this.chkdata)
            {
                int rowIndex = 0;
                foreach (CDEEntity entity in listEntity)
                {
                    if (aryChk[rowIndex] != "0")
                    {
                        dr = dt.NewRow();
                        for (int index = 0; index < dt.Columns.Count; index++)
                        {
                            string name = dt.Rows[0][index].ToString();
                            string value = StringWithXml.getObject2String(entity.get(name));
                            CDEColumn pclm = moto_em.getAttribute(name).getP_Colmun();
                            if (value != string.Empty && pclm.isHaveCandidate())
                            {
                                List<CDECandidate> listCandidate = pclm.getCandidates();
                                foreach (CDECandidate candidate in listCandidate)
                                {
                                    if (candidate.Value == value)
                                    {
                                        dr[index] = candidate.Label;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                dr[index] = ConstDataType.STRING.Equals(moto_em.getAttribute(name).getP_Colmun().Type) ? "'" + value : entity.get(name);
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                    rowIndex++;
                }
            }
            else
            {
                foreach (CDEEntity entity in listEntity)
                {
                    dr = dt.NewRow();
                    for (int index = 0; index < dt.Columns.Count; index++)
                    {
                        string name = dt.Rows[0][index].ToString();
                        string value = StringWithXml.getObject2String(entity.get(name));
                        CDEColumn pclm = moto_em.getAttribute(name).getP_Colmun();
                        if (value != string.Empty && pclm.isHaveCandidate())
                        {
                            List<CDECandidate> listCandidate = pclm.getCandidates();
                            foreach (CDECandidate candidate in listCandidate)
                            {
                                if (candidate.Value == value)
                                {
                                    dr[index] = candidate.Label;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            dr[index] = ConstDataType.STRING.Equals(moto_em.getAttribute(name).getP_Colmun().Type) ? "'" + value : entity.get(name);
                        }
                    }
                    dt.Rows.Add(dr);
                }
            }
            //dt.Rows[0][0] = dt.Columns.Count;
            //dt.Rows[0][1] = dt.Rows.Count;
            ExcelIO excelIO = new ExcelIO();
            excelIO.writeTableDataToExcel(templateFileName, dt);
        }
        catch (Exception e)
        {
            UserControl.Log.SaveException(e);
        }        
        finally
        {
        }
    }
    private void excelDownload(string templateFileName)
    {
        //ファイルダウンロードダイアログを表示する
        FileInfo DownloadFile = new FileInfo(templateFileName);
        if (DownloadFile.Exists == true)
        {
            Response.Clear();
            Response.ClearHeaders();
            Response.Buffer = false;
            Encoding encodeShiftJIS = Encoding.GetEncoding("UTF-8");
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename="
                + HttpUtility.UrlEncode("EXCELTemplate.xls", encodeShiftJIS));
            Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            Response.WriteFile(DownloadFile.FullName);
            Response.Flush();
            DownloadFile.Delete();
            Response.End();
        }
    }
    protected void printWrite()
    {
        try
        {
            string[] aryChk = this.chkFlg.Split(',');
            List<CDEEntity> listEntity = CDEService.LoadEntities(moto_em, sc);

            System.Data.DataTable dt = new System.Data.DataTable();
            System.Data.DataRow dr;
            foreach (CDEAttribute cdeAttrheader in moto_em.ListAttributes)
            {
                dt.Columns.Add(new DataColumn(cdeAttrheader.Label, typeof(string)));
            }

            int colIndex = 0;
            if (this.chkdata)
            {
                int rowIndex = 0;
                foreach (CDEEntity entity in listEntity)
                {
                    if (aryChk[rowIndex] != "0")
                    {
                        dr = dt.NewRow();
                        colIndex = 0;
                        foreach (CDEAttribute cdeAttr in moto_em.ListAttributes)
                        {
                            dr[colIndex] = entity.get(cdeAttr.Name);
                            colIndex++;
                        }
                        dt.Rows.Add(dr);
                    }
                    rowIndex++;
                }
            }
            else
            {
                foreach (CDEEntity entity in listEntity)
                {
                    dr = dt.NewRow();
                    colIndex = 0;
                    foreach (CDEAttribute cdeAttr in moto_em.ListAttributes)
                    { 
                        dr[colIndex] = entity.get(cdeAttr.Name);
                        colIndex++;
                    }
                    dt.Rows.Add(dr);
                }
            }

            Session["TEMP_PRINT_DATATABLE"] = dt;
            Session["TEMP_PRINT_PAGETITLE"] = moto_em.Label;

            StringBuilder sbr = new StringBuilder();
            sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);

            sbr.AppendFormat("var wOpen;", Environment.NewLine);
            sbr.AppendFormat("wOpen = window.open(\"PrintPage.aspx\",\"popupPrintPage\", \"toolbar=yes,menubar=yes,scrollbars=auto,resizable=yes,location=no,directories=no,top=0,left=0,width=1005,height=755\");", Environment.NewLine);
            sbr.AppendFormat("wOpen.focus();", Environment.NewLine);
            sbr.AppendFormat("window.close();", Environment.NewLine);
            sbr.AppendFormat("</script>{0}", Environment.NewLine);
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sbr.ToString());


        }
        catch (Exception e)
        {
            UserControl.Log.SaveException(e);
        }
        finally
        {
        }
    }
    private void closeWindow()
    {
        StringBuilder sbr = new StringBuilder();
        sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
        sbr.AppendFormat("window.close();{0}", Environment.NewLine);
        sbr.AppendFormat("</script>{0}", Environment.NewLine);
        Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sbr.ToString());
    }
}
